<template>
  <div id="app-base-socket-ipc">
    <div class="left-wrapper" :class="{ active: xinVisible }">
      <div class="one-block-1">
        <h3 class="title">账号管理</h3>
        <a-button type="text" @click="handleConfig"
          ><icon-settings size="24"
        /></a-button>
      </div>
      <div class="one-block-2">
        <a-space>
          <a-button
            type="primary"
            status="warning"
            size="large"
            class="sales-num"
            ><small><icon-gift />直播销售总额</small>
            <span>{{ configInfo.priceSum }}</span></a-button
          >
          <div class="btn-group">
            <a-space style="margin-bottom: 10px">
              <a-button type="primary" @click="newAccount" :loading="newLoading"
                >新增账号</a-button
              >
              <a-button
                type="text"
                style="
                  background: var(--color-fill-3);
                  color: #fff;
                  width: 172px;
                "
                >{{ selectedRow.dyuserNickname }}</a-button
              >
              <a-button type="primary">备注</a-button>
              <a-button type="primary" @click="handleStart('2')">启动</a-button>
              <a-button type="primary" @click="handleStart('1')"
                >全部启动</a-button
              >
              <a-button type="primary">显示</a-button>
              <a-button type="primary">隐藏</a-button>
            </a-space>
            <a-space>
              <a-button type="primary" status="danger" @click="removeAccount"
                >删除账号</a-button
              >
              <a-select
                v-model="selectKF"
                :style="{ width: '120px' }"
                placeholder="客服"
                :trigger-props="{ autoFitPopupMinWidth: true }"
                ><a-option
                  v-for="kf in kfOptions"
                  :key="kf.kfId"
                  :value="kf.kfId"
                  >{{ kf.kfName }}</a-option
                >
                <!-- <a-option>客服01</a-option>
              <a-option>客服</a-option> -->
              </a-select>
              <a-select
                v-model="selectCK"
                :style="{ width: '112px' }"
                placeholder="场控"
                :trigger-props="{ autoFitPopupMinWidth: true }"
              >
                <a-option
                  v-for="ck in ckOptions"
                  :key="ck.ckId"
                  :value="ck.ckId"
                  >{{ ck.ckName }}</a-option
                >
                <!-- <a-option>场控</a-option> -->
              </a-select>
              <a-button type="primary" status="danger" @click="handleStop('2')"
                >停止</a-button
              >
              <a-button type="primary" status="danger" @click="handleStop('1')"
                >全部停止</a-button
              >
              <a-button
                type="primary"
                status="danger"
                @click="handleSecKill('1')"
                >秒杀</a-button
              >
              <a-button
                type="primary"
                status="danger"
                @click="handleSecKill('2')"
                >下架</a-button
              >
            </a-space>
          </div>
        </a-space>
        <div class="table-wrapper">
          <a-table
            :data="tabList"
            :bordered="{ wrapper: true, cell: true }"
            header-cell-class="tab-thead"
            row-key="dyuserId"
            v-model:selectedKeys="selectedIds"
            :pagination="false"
            :sticky-header="true"
            @row-click="rowClick"
            @cell-click="handleXin"
          >
            <template #columns>
              <a-table-column
                title="序"
                data-index="dyuserNum"
                width="80"
                align="center" />
              <a-table-column
                title="ID"
                data-index="dyuserId"
                width="80"
                align="center" />
              <a-table-column
                title="账号昵称"
                data-index="dyuserNickname"
                width="120"
                align="center" />
              <a-table-column
                title="状态"
                data-index="driverstatus"
                width="120"
              >
                <template #cell="{ record }">
                  <i
                    class="status-ico"
                    :style="{
                      background:
                        record[4] === '1'
                          ? '#00b42a'
                          : record[4] === '2'
                          ? '#ff0000'
                          : '#999999',
                    }"
                  ></i>
                  <span>{{
                    record[4] === '1'
                      ? '运行中'
                      : record[4] === '2'
                      ? '未运行'
                      : '未注册完成'
                  }}</span>
                </template>
              </a-table-column>
              <a-table-column
                title="任务日志"
                data-index="logstatus "
                width="100" />
              <a-table-column
                title="在线"
                data-index="onlinePeper"
                width="70" />
              <a-table-column
                title="销售额"
                data-index="price"
                align="center" />
              <a-table-column
                title="备注"
                data-index="dyuserRemark"
                align="center" />
              <a-table-column
                title="秒杀"
                data-index="msStatus"
                align="center" />
              <a-table-column title="信" data-index="plStatus" align="center" />
              <a-table-column
                title="违规"
                data-index="11"
                align="center" /></template
          ></a-table>
        </div>
      </div>
    </div>
    <div class="xin-wrapper" v-if="xinVisible">
      <div class="danmu">
        <div class="title">
          <h3>弹幕</h3>
          <a-button
            type="text"
            style="color: #fff"
            class="close-btn"
            @click="handleCloseXin"
            >X</a-button
          >
        </div>
        <div class="contents">
          <p v-for="(dm, index) in danmuList" :key="index">
            {{ dm.username }}: {{ dm.desc }}
          </p>
        </div>
      </div>
      <div class="send-wrapper">
        <a-input type="textarea" v-model="danmuInput"></a-input>
        <a-button type="primary" @click="sendDanmu">发送</a-button>
      </div>
    </div>
    <!-- 设置弹框 -->
    <a-modal
      v-model:visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      :hide-cancel="true"
      title="全局设置"
      title-align="start"
      :width="280"
      body-class="modal-content"
    >
      <div>
        <p>
          <span>
            <label>自动秒杀时间：</label
            ><a-input
              class="conf-input"
              v-model="configFrom.seckillTime"
            ></a-input
            >分钟</span
          ><a-switch
            type="round"
            v-model="configFrom.seckill"
            checked-color="#00ff00"
          />
        </p>
        <p>
          <span
            ><label>讲解时间：</label
            ><a-input
              class="conf-input"
              v-model="configFrom.explainsTime"
            ></a-input
            >秒</span
          ><a-switch
            type="round"
            v-model="configFrom.explains"
            checked-color="#00ff00"
          />
        </p>
        <p>
          <span
            ><label>场控时间：</label
            ><a-input
              class="conf-input"
              v-model="configFrom.filedcontrolTime"
            ></a-input
            >秒</span
          ><a-switch
            type="round"
            v-model="configFrom.filedControl"
            checked-color="#00ff00"
          />
        </p>
        <p>
          <label>语音提醒</label
          ><a-switch
            type="round"
            v-model="configFrom.voiceControl"
            checked-color="#00ff00"
          />
        </p>
      </div>
      <template #footer>
        <div style="text-align: center">
          <a-button type="primary" @click="handleOk">保 存</a-button>
        </div>
      </template>
    </a-modal>
    <a-modal
      :visible="confirmVisible"
      title="提示"
      @ok="handleYes"
      @cancel="handleNo"
      :width="280"
      >确定删除该账户吗？</a-modal
    >
  </div>
</template>
<script>
import { ipcApiRoute, specialIpcRoute } from '@/utils/ipcMainApi'
import { ipc, cptext } from '@/utils/ipcRenderer'
import Login from '@/views/vueui/login/Window.vue'
import {
  getUserList,
  initNewUser,
  removeUser,
  getConfig,
  updateConfig,
  getCKList,
  getKFList,
  startDriver,
  closeDriver,
  seckillAll,
} from '@/services'
export default {
  components: { Login },
  data() {
    return {
      xinVisible: false,
      danmuInput: '',
      danmuList: [
        {
          username: '哈哈哈哈',
          desc: '电话费会计核算的空间饭后漱口撒打算几点睡客服经理说肯德基刚开始',
        },
        {
          username: '你说啥',
          desc: '风太大我听不见',
        },
      ],
      confirmVisible: false,
      newLoading: false, // 新增账号loading
      columns: [
        {
          title: '序',
          dataIndex: 'dyuserNum',
        },
        {
          title: 'ID',
          dataIndex: 'dyuserId',
        },
        {
          title: '账号昵称',
          dataIndex: 'dyuserNickname',
        },
        {
          title: '状态',
          dataIndex: 'driverstatus',
        },
        {
          title: '任务日志',
          dataIndex: 'logstatus',
        },
        {
          title: '在线',
          dataIndex: 'onlinePeper',
        },
        {
          title: '销售额',
          dataIndex: 'price',
        },
        {
          title: '备注',
          dataIndex: 'dyuserRemark',
        },
        {
          title: '秒杀',
          dataIndex: 'msStatus',
        },
        {
          title: '信',
          dataIndex: 'plStatus',
        },
        {
          title: '违规',
          dataIndex: '11',
        },
      ],
      tabList: [
        {
          key: '1',
          no: '1',
          2: 826966,
          3: 'London',
          4: '运行中',
          5: 'Jane Doe',
          6: 23000,
          7: '32 Park Road',
          8: 'jane.doe@example',
          9: 'Jane Doe',
          10: 23000,
          11: '32 Park Road, London',
        },
        {
          key: '2',
          no: '2',
          2: 826967,
          3: 'London',
          4: '未运行',
          5: 'Jane Doe',
          6: 23000,
          7: '32 Park Road',
          8: 'jane.doe@example',
          9: 'Jane Doe',
          10: 23000,
          11: '32 Park Road, London',
        },
      ],
      configFrom: {
        seckillTime: '',
        seckill: false,
        explainsTime: '',
        explains: false,
        filedcontrolTime: '',
        filedControl: false,
        voiceControl: false,
      },
      configInfo: {},
      total: 0,
      visible: false, // 是否显示全局设置弹框
      selectedIds: [], // 选择的账户id
      selectedRow: {},
      selectKF: '',
      selectCK: '',
      // pagination: {
      // pageSize: 5,
      // pageNum: 1,
      // },
      kfOptions: [],
      ckOptions: [],
    }
  },
  mounted() {
    this.initData()
    this.getConfigInfo()
    this.getCKoptions()
    this.getKFOptions()
    // this.init()
    // this.initBySocket()
  },
  methods: {
    // websocket
    initBySocket() {
      // const ws = new WebSocket("ws://localhost:3001");
      const ws = new WebSocket('ws://eos.douyin.com')

      ws.onopen = (event) => {
        console.log('Connected to Server')
        ws.send('Hello, server!')
      }
      ws.onmessage = (event) => {
        console.log('Received from Server:', event.data)
      }
      ws.onclose = (event) => {
        console.log('Websocket connection closed.')
      }
      ws.onerror = (error) => {
        console.log('Websocket error:', error)
      }
    },
    // click信
    handleXin(record, column, ev) {
      if (column.dataIndex === 'plStatus') {
        console.log(record, column, ev)
        this.xinVisible = true
      }
    },
    // 发送弹幕
    sendDanmu() {
      if (this.danmuInput) {
        console.log(this.danmuInput)
        this.danmuList.push({
          username: this.selectedRow.dyuserNickname,
          desc: this.danmuInput,
        })
        this.danmuInput = ''
      }
    },
    // 关闭弹幕
    handleCloseXin() {
      this.xinVisible = false
    },
    // 启动(1启动全部，2启动当前账户）
    async handleStart(type) {
      try {
        const res = await startDriver({ dyuserId: this.selectedIds[0], type })
        this.$message.success(type === '1' ? '已全部启动' : '当前用户已启动')
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 停止(1全部，2当前账户）
    async handleStop(type) {
      try {
        const res = await closeDriver({ dyuserId: this.selectedIds[0], type })
        this.$message.success(type === '1' ? '已全部停止' : '当前用户已停止')
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 秒杀/下架 (1秒杀，2取消秒杀）
    async handleSecKill(type) {
      try {
        const res = await seckillAll({ dyuserId: this.selectedIds[0], type })
        this.$message.success(type === '1' ? '已开启秒杀' : '已下架')
      } catch (error) {
        this.$message.error(error)
      }
    },
    async getKFOptions() {
      try {
        const res = await getKFList()
        this.kfOptions = res.rows
      } catch (error) {
        this.$message.error(error)
      }
    },
    async getCKoptions() {
      try {
        const res = await getCKList()
        this.ckOptions = res.rows
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 新增账号-初始化、创建
    async newAccount() {
      this.newLoading = true
      try {
        await initNewUser()
        await createNewUser({ dyuserId: 1 })
        this.initData()
        this.newLoading = false
      } catch (error) {
        this.newLoading = false
        this.$message.error(error)
      }
    },
    rowClick(row, e) {
      // console.log(row)
      const idx = this.selectedIds.findIndex((item) => row.dyuserId === item)
      if (idx > -1) {
        // this.selectedIds.splice(idx, 1)
        // this.selectedRow = {}
        // this.selectCK = ''
        // this.selectKF = ''
      } else if (this.selectedIds.length) {
        this.selectedIds.splice(0, this.selectedIds.length)
        this.selectedIds.push(row.dyuserId)
        this.selectedRow = row
        this.selectCK = row.ckId
        this.selectKF = row.kfId
      } else {
        this.selectedIds.push(row.dyuserId)
        this.selectedRow = row
        this.selectCK = row.ckId
        this.selectKF = row.kfId
      }
      // console.log(this.selectedIds)
    },
    removeAccount() {
      this.confirmVisible = true
    },
    // 更新设置
    async handleOk() {
      try {
        const res = await updateConfig({
          seckillTime: this.configFrom.seckillTime,
          seckill: this.configFrom.seckill ? '1' : '2', // 1 表示开启，2 表示不开启。
          explainsTime: this.configFrom.explainsTime,
          explains: this.configFrom.explains ? '1 ' : '2',
          filedcontrolTime: this.configFrom.filedcontrolTime,
          filedControl: this.configFrom.filedControl ? '1' : '2',
          voiceControl: this.configFrom.voiceControl ? '1' : '2',
          userId: this.configInfo.userId,
        })
        this.$message.success('操作成功！')
        this.visible = false
        this.getConfigInfo()
      } catch (error) {
        this.$message.error(error)
        this.visible = false
      }
    },
    async getConfigInfo() {
      try {
        const res = await getConfig()
        console.log(res)
        this.configInfo = res.data
        this.configFrom.seckillTime = this.configInfo.seckillTime
        this.configFrom.seckill = this.configInfo.seckill === '1' ? true : false
        this.configFrom.explainsTime = this.configInfo.explainsTime
        this.configFrom.explains =
          this.configInfo.explains === '1' ? true : false
        this.configFrom.filedcontrolTime = this.configInfo.filedcontrolTime
        this.configFrom.filedControl =
          this.configInfo.filedControl === '1' ? true : false
        this.configFrom.voiceControl =
          this.configInfo.voiceControl === '1' ? true : false
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 全局设置功能
    handleConfig() {
      this.visible = true
      // this.getConfigInfo()
    },
    async initData() {
      try {
        const res = await getUserList()
        console.log(res)
        this.tabList = res.rows
        this.selectedRow = this.tabList.length ? this.tabList[0] : {}
        this.total = res.total
        if (res && res.rows && res.rows.length) {
          this.selectedIds.push(res.rows[0].dyuserId)
          this.selectKF = res.rows[0].kfId
          this.selectCK = res.rows[0].ckId
        }
      } catch (error) {
        this.$message.error(error)
      }
    },
    async handleYes() {
      try {
        await removeUser({ ids: this.selectedIds[0] })
        this.confirmVisible = false
        this.initData()
      } catch (error) {
        this.$message.error(error)
        this.confirmVisible = false
      }
    },
    handleNo() {
      this.confirmVisible = false
    },
    init() {
      // 避免重复监听，或者将 on 功能写到一个统一的地方，只加载一次
      ipc.removeAllListeners(ipcApiRoute.ipcSendMsg)
      ipc.on(ipcApiRoute.ipcSendMsg, (event, result) => {
        console.log('[ipcRenderer] [socketMsgStart] result:', result)

        this.messageString = result
        // 调用后端的另一个接口
        event.sender.send(ipcApiRoute.hello, 'electron-egg')
      })

      // 监听 窗口2 发来的消息
      ipc.removeAllListeners(specialIpcRoute.window2ToWindow1)
      ipc.on(specialIpcRoute.window2ToWindow1, (event, arg) => {
        this.$message.info(arg)
      })
    },
  },
}
</script>
<style lang="less" scoped>
#app-base-socket-ipc {
  padding: 0px 10px;
  text-align: left;
  width: 100%;
  display: flex;
  .left-wrapper.active {
    width: 72%;
  }
  .xin-wrapper {
    // flex: 1;
    width: 25%;
    height: 500px;
    background: #333;
    box-sizing: border-box;
    margin-top: 20px;
    margin-right: 10px;
    .danmu {
      border: 2px solid #999;
      margin-bottom: 10px;
    }
    .contents {
      height: calc(100vh - 130px);
      padding: 5px;
      color: #00ff00;
    }
    .title {
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 40px;
      background: rgb(var(--arcoblue-6));
      text-indent: 10px;
    }
    .send-wrapper {
      display: flex;
    }
  }
  .one-block-1 {
    font-size: 16px;
    padding-top: 10px;
    h3.title {
      display: inline-block;
      padding-right: 10px;
      position: relative;
      top: -5px;
    }
  }
  .one-block-2 {
    padding-top: 10px;
    .sales-num {
      min-width: 180px;
      height: 75px;
      font-size: 36px;
      font-weight: bold;
      position: relative;

      small {
        position: absolute;
        top: -10px;
        left: 33px;
        font-size: 14px;
        // background: var(--) !important;
        background: #333;
        padding: 0px 5px;
        border-radius: 4px;
      }
    }
    .btn-group .arco-btn {
      font-weight: bold;
    }
  }
  .table-wrapper {
    margin-top: 20px;
    padding-right: 20px;
    .status-ico {
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: gray;
      position: relative;
      top: -1px;
      left: -5px;
    }
    :deep(.arco-table-th) {
      background: rgb(var(--arcoblue-6));
    }
  }
}
.conf-input {
  width: 50px;
  :deep(.arco-input) {
    width: 40px;
  }
}

.modal-content {
  b {
    background: #333;
    display: inline-block;
    width: 40px;
    text-align: center;
    margin-right: 5px;
  }
  p {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
